package com.tjian.fafa.user.module.home.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Parcelable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.radar.RadarNearbyInfo;
import com.baidu.mapapi.radar.RadarNearbyResult;
import com.baidu.mapapi.radar.RadarNearbySearchOption;
import com.baidu.mapapi.radar.RadarSearchError;
import com.baidu.mapapi.radar.RadarSearchListener;
import com.baidu.mapapi.radar.RadarSearchManager;
import com.baidu.mapapi.radar.RadarUploadInfo;
import com.baidu.mapapi.radar.RadarUploadInfoCallback;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.tjian.fafa.user.R;
import com.tjian.fafa.user.base.bean.UserInfo;
import com.tjian.fafa.user.base.util.user.UserUtil;
import com.tjian.fafa.user.config.ConfigOfFafa;
import com.tjian.fafa.user.module.home.adapter.NewsAdapter;
import com.tjian.fafa.user.module.home.bean.NewsEntity;
import com.tjian.fafa.user.module.home.service.NewsFragmentService;
import com.tjian.fafa.user.module.home.tool.Constants_home;

import java.util.ArrayList;
import java.util.List;

import baidumapsdk.demo.CustomViewPager;

public class Develop_test_page_home_fragment extends Fragment implements OnGetGeoCoderResultListener, RadarUploadInfoCallback,
        RadarSearchListener, BDLocationListener, OnMarkerClickListener, OnMapClickListener
{
    ArrayList<NewsEntity> newsList = new ArrayList<NewsEntity>();
    ListView mListView;
    NewsAdapter mAdapter;
    String text;
    ImageView detail_loading;
    public final static int SET_NEWSLIST = 0;

    // 定位相关
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;

    // UI相关
    RadioGroup.OnCheckedChangeListener radioButtonListener;
    Button requestLocButton;
    boolean isFirstLoc = true; // 是否首次定位
    GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用

    // 界面空间相关
    private CustomViewPager mPager; // 自定义viewPager，目的是禁用手势滑动
    private List<View> listViews;
    private TabHost mTabHost;
    private EditText userId;
    private EditText userDes;

    private Button stopUpload;
    private Button switchBtn;
    private Button searchNearbyBtn;
    private Button clearRstBtn;
    private Button clearInfoBtn;
    private int index = 0;
    private Button listPreBtn;
    private Button listNextBtn;
    private TextView listCurPage;
    private Button mapPreBtn;
    private Button mapNextBtn;
    private TextView mapCurPage;

    // 定位相关
    LocationClient mLocClient;
    private int pageIndex = 0;
    private int curPage = 0;
    private int totalPage = 0;
    private LatLng pt = null;

    // 周边雷达相关
    RadarNearbyResult listResult = null;
    ListView mResultListView = null;
    RadarResultListAdapter mResultListAdapter = null;
    private String userID = "";
    private String userComment = "";
    private boolean uploadAuto = ConfigOfFafa.uploadAuto;

    // 地图相关
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private TextView popupText = null; // 泡泡view
    BitmapDescriptor ff3 = BitmapDescriptorFactory.fromResource(R.drawable.icon_marka);

    private NewsFragmentService newsFragmentService;

    Handler handler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        Bundle args = getArguments();
        text = args != null ? args.getString("text") : "";
        initData();
        super.onCreate(savedInstanceState);

        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }*/


    }

    /**
     * 此方法意思为fragment是否可见 ,可见时候加载数据
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser)
    {
        if (isVisibleToUser)
        {
            //fragment可见时加载数据
            if (newsList != null && newsList.size() != 0)
            {
                handler.obtainMessage(SET_NEWSLIST).sendToTarget();
            }
            else
            {
                new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            Thread.sleep(2);
                        }
                        catch (InterruptedException e)
                        {
                            e.printStackTrace();
                        }
                        handler.obtainMessage(SET_NEWSLIST).sendToTarget();
                    }
                }).start();
            }
        }
        else
        {
            //fragment不可见时不执行操作
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.activity_radartab_home_layout, null);

        //        initOLdNewsListView(view);//加载旧的新闻列表
        //        showDiliverymanByLatAndLon();//显示周边配送员

        onCreateRadar(view);//创建雷达视图

        uploadContinueTimerControl();//上传当前用户信息到百度地图服务器
        //        uploadOnceClick();//上传一次

        return view;
    }

    public void onCreateRadar(View view)
    {
        // 初始化UI和地图
        initUI(view);
        // 周边雷达设置监听
        RadarSearchManager.getInstance().addNearbyInfoListener(this);
        // 周边雷达设置用户，id为空默认是设备标识
        RadarSearchManager.getInstance().setUserID(userID);

        // 定位初始化
        mLocClient = new LocationClient(getActivity());
        mLocClient.registerLocationListener(this);



        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(false); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();

    }

    private void initData()
    {
        newsList = Constants_home.getNewsList();
    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener
    {

        @Override
        public void onReceiveLocation(BDLocation location)
        {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
            {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc)
            {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
            }
        }

        public void onReceivePoi(BDLocation poiLocation)
        {
        }
    }

    public void initOLdNewsListView(View view)
    {
        mListView = (ListView) view.findViewById(R.id.mListView);
        detail_loading = (ImageView) view.findViewById(R.id.detail_loading);
    }

    /**
     * 解码周边的配送员，用图标显示出来
     */
    public void showDiliverymanByLatAndLon()
    {
        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);

        LatLng ptCenter = new LatLng((Float.valueOf("39.904965")), (Float.valueOf("116.327764")));
        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter));// 反Geo搜索

        //        LatLng ptCenter2 = new LatLng((Float.valueOf("39.904965")), (Float.valueOf("116.327764")));
        LatLng ptCenter2 = new LatLng((Float.valueOf("39.914965")), (Float.valueOf("116.317764")));
        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter2));// 反Geo搜索
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult result)
    {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR)
        {
            Toast.makeText(getActivity(), "抱歉，未能找到结果_20160203_104521", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        mBaiduMap.clear();
        mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.icon_marka)));
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result
                .getLocation()));
        String strInfo = String.format("纬度：%f 经度：%f",
                result.getLocation().latitude, result.getLocation().longitude);
        Toast.makeText(getActivity(), strInfo, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result)
    {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR)
        {
            Toast.makeText(getActivity(), "抱歉，未能找到结果_20160203_104527", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        mBaiduMap.clear();
        mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.icon_marka)));
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result
                .getLocation()));
        Toast.makeText(getActivity(), result.getAddress(),
                Toast.LENGTH_LONG).show();

    }

    private void initUI(View view)
    {
        mTabHost = (TabHost) view.findViewById(R.id.tabhost);
        mTabHost.setup();
        mTabHost.addTab(mTabHost.newTabSpec("tabUpload")
                .setIndicator(composeLayout("上传位置", 0))
                .setContent(R.id.tabUpload));
        mTabHost.addTab(mTabHost.newTabSpec("tabGet")
                .setIndicator(composeLayout("检索周边", 0))
                .setContent(R.id.tabGet));
        mTabHost.setCurrentTab(0);

        mTabHost.setOnTabChangedListener(new OnTabChangeListener()
        {
            @Override
            public void onTabChanged(String tabId)
            {
                for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++)
                {
                    mTabHost.getTabWidget().getChildAt(i).setBackgroundDrawable(null);
                }
                mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab())
                        .setBackgroundColor(Color.parseColor("#B0E2FF"));
            }

        });

        mPager = (CustomViewPager) view.findViewById(R.id.viewpager);
        listViews = new ArrayList<View>();
        LayoutInflater mInflater = getActivity().getLayoutInflater();

        View layout = mInflater.inflate(R.layout.activity_radarlist, null);
        View mapLayout = mInflater.inflate(R.layout.activity_radarmap, null);
        // 地图初始化
        mMapView = (MapView) mapLayout.findViewById(R.id.map);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setOnMarkerClickListener(this);
        mBaiduMap.setOnMapClickListener(this);
        mBaiduMap.setMyLocationEnabled(true);
        listViews.add(layout);
        listViews.add(mapLayout);
        mPager.setAdapter(new MyPagerAdapter(listViews));
        mPager.setCurrentItem(0);
        mPager.setOnPageChangeListener(new MyOnPageChangeListener());

        userId = (EditText) view.findViewById(R.id.id);
        userDes = (EditText) view.findViewById(R.id.des);

        stopUpload = (Button) view.findViewById(R.id.stopupload);
        stopUpload.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                stopUploadClick();
            }
        });

        switchBtn = (Button) view.findViewById(R.id.switchButton);
        switchBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                switchClick();
            }
        });

        searchNearbyBtn = (Button) view.findViewById(R.id.searchNearByButton);
        searchNearbyBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                searchNearby();
            }
        });

        clearRstBtn = (Button) view.findViewById(R.id.clearResultButton);
        clearRstBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                clearResult();
            }
        });

        clearInfoBtn = (Button) view.findViewById(R.id.clearInfoButton);
        clearInfoBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                clearInfoClick();
            }
        });


        listPreBtn = (Button) layout.findViewById(R.id.radarlistpre);
        listNextBtn = (Button) layout.findViewById(R.id.radarlistnext);
        listCurPage = (TextView) layout.findViewById(R.id.radarListPage);
        mapPreBtn = (Button) mapLayout.findViewById(R.id.radarmappre);
        mapNextBtn = (Button) mapLayout.findViewById(R.id.radarmapnext);
        mapCurPage = (TextView) mapLayout.findViewById(R.id.radarMapPage);

        stopUpload.setEnabled(true);
        clearRstBtn.setEnabled(false);
        clearInfoBtn.setEnabled(true);
        listPreBtn.setVisibility(View.INVISIBLE);
        listNextBtn.setVisibility(View.INVISIBLE);
        mapPreBtn.setVisibility(View.INVISIBLE);
        mapNextBtn.setVisibility(View.INVISIBLE);
        listCurPage.setVisibility(View.INVISIBLE);
        mapCurPage.setVisibility(View.INVISIBLE);

        mTabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.DKGRAY);
        ArrayList<RadarNearbyInfo> infos = new ArrayList<RadarNearbyInfo>();
        mResultListAdapter = new RadarResultListAdapter(null);
        mResultListView = (ListView) layout.findViewById(R.id.radar_list);
        mResultListView.setAdapter(mResultListAdapter);
        mResultListAdapter.notifyDataSetChanged();

        /*发送当前登录用户的信息到百度地图服务器*/
        UserInfo userInfo = UserUtil.obtainLoginUser(getActivity());
        if (userInfo != null)
        {
            userID = String.valueOf(userInfo.getId());
            String mName = userInfo.getName();
            userComment = "备注"+mName;
            //上传的用户的id
            RadarSearchManager.getInstance().setUserID(userID);
        }
    }

    /**
     * 开始自动上传
     */
    public void uploadContinueClick()
    {
        if (pt == null)
        {
            Toast.makeText(getActivity(), "未获取到位置", Toast.LENGTH_LONG).show();
            return;
        }
        uploadAuto = true;
        RadarSearchManager.getInstance().startUploadAuto(this, 5000);//5秒上传1次
        stopUpload.setEnabled(true);
        clearInfoBtn.setEnabled(true);
    }

    /**
     * 自动上传控制器
     */
    public void uploadContinueTimerControl()
    {
        if (pt != null)
        {
            uploadContinueClick();
        }
        if (pt == null)
        {
            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    Looper.prepare();
                    try
                    {
                        Thread.sleep(1 * 1000);//如果还没有收到百度地图返回的定位信息，等1秒再执行一次，直到得到信息，上传到百度地图的服务器
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    Looper.loop();
                    handler.post(runnable); //线程可以更新结果了
                }
            }).start();
        }
    }

    final Runnable runnable = new Runnable()
    {
        public void run()
        {
            uploadContinueTimerControl();
        }
    };

    /**
     * 上传一次位置
     */
    public void uploadOnceClick()
    {
        if (pt == null)
        {
            Toast.makeText(getActivity(), "未获取到位置", Toast.LENGTH_LONG).show();
            return;
        }
        RadarUploadInfo info = new RadarUploadInfo();
        info.comments = userComment;
        info.pt = pt;
        RadarSearchManager.getInstance().uploadInfoRequest(info);
        clearInfoBtn.setEnabled(true);
    }

    /**
     * 停止自动上传
     */
    public void stopUploadClick()
    {
        uploadAuto = false;
        RadarSearchManager.getInstance().stopUploadAuto();
        stopUpload.setEnabled(true);
    }

    /**
     * 清除自己当前的信息
     */
    public void clearInfoClick()
    {
        RadarSearchManager.getInstance().clearUserInfo();
    }

    /**
     * 查找周边的人
     */
    public void searchNearby()
    {
        if (pt == null)
        {
            Toast.makeText(getActivity(), "未获取到位置", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        pageIndex = 0;
        searchRequest(pageIndex);
    }

    /**
     * 上一页
     *
     * @param v
     */
    public void preClick(View v)
    {
        if (pageIndex < 1)
        {
            return;
        }
        // 上一页
        pageIndex--;
        searchRequest(pageIndex);
    }

    /**
     * 下一页
     *
     * @param v
     */
    public void nextClick(View v)
    {
        if (pageIndex >= totalPage - 1)
        {
            return;
        }
        // 下一页
        pageIndex++;
        searchRequest(pageIndex);
    }

    private void searchRequest(int index)
    {
        curPage = 0;
        totalPage = 0;

        RadarNearbySearchOption option =
                new RadarNearbySearchOption().centerPt(pt).pageNum(pageIndex).radius(2000).pageCapacity(11);

        RadarSearchManager.getInstance().nearbyInfoRequest(option);

        listPreBtn.setVisibility(View.INVISIBLE);
        listNextBtn.setVisibility(View.INVISIBLE);
        mapPreBtn.setVisibility(View.INVISIBLE);
        mapNextBtn.setVisibility(View.INVISIBLE);
        listCurPage.setText("0/0");
        mapCurPage.setText("0/0");
        mBaiduMap.hideInfoWindow();
    }

    /**
     * 清除查找结果
     */
    public void clearResult()
    {
        parseResultToList(null);
        parseResultToMap(null);
        clearRstBtn.setEnabled(false);
        listPreBtn.setVisibility(View.INVISIBLE);
        listNextBtn.setVisibility(View.INVISIBLE);
        mapPreBtn.setVisibility(View.INVISIBLE);
        mapNextBtn.setVisibility(View.INVISIBLE);
        listCurPage.setVisibility(View.INVISIBLE);
        mapCurPage.setVisibility(View.INVISIBLE);
        mBaiduMap.hideInfoWindow();
    }

    // viewPager切换
    public void switchClick()
    {
        if (index == 0)
        {
            // 切换为地图
            index = 1;
            switchBtn.setText("列表");
        }
        else
        {
            // 切换为列表
            index = 0;
            switchBtn.setText("地图");
        }
        mPager.setCurrentItem(index);
    }

    /**
     * 更新结果列表
     *
     * @param res
     */
    public void parseResultToList(RadarNearbyResult res)
    {
        if (res == null)
        {
            if (mResultListAdapter.list != null)
            {
                mResultListAdapter.list.clear();
                mResultListAdapter.notifyDataSetChanged();
            }

        }
        else
        {
            mResultListAdapter.list = res.infoList;
            mResultListAdapter.notifyDataSetChanged();
            if (curPage > 0)
            {
                listPreBtn.setVisibility(View.VISIBLE);
            }
            if (totalPage - 1 > curPage)
            {
                listNextBtn.setVisibility(View.VISIBLE);
            }
            if (totalPage > 0)
            {
                listCurPage.setVisibility(View.VISIBLE);
                listCurPage.setText(String.valueOf(curPage + 1) + "/" + String.valueOf(totalPage));
            }

        }

    }

    /**
     * 更新结果地图
     *
     * @param res
     */
    public void parseResultToMap(RadarNearbyResult res)
    {
        mBaiduMap.clear();
        if (res != null && res.infoList != null && res.infoList.size() > 0)
        {
            for (int i = 0; i < res.infoList.size(); i++)
            {
                //                String userID = res.infoList.get(i).userID;

                MarkerOptions option = new MarkerOptions().icon(ff3).position(res.infoList.get(i).pt);
                Bundle extraInfoBundle = new Bundle();
                if (res.infoList.get(i).comments == null || res.infoList.get(i).comments.equals(""))
                {
                    extraInfoBundle.putString("des", "没有备注");
                }
                else
                {
                    extraInfoBundle.putString("des", res.infoList.get(i).comments);
                }

                option.extraInfo(extraInfoBundle);
                mBaiduMap.addOverlay(option);
            }
        }
        if (curPage > 0)
        {
            mapPreBtn.setVisibility(View.VISIBLE);
        }
        if (totalPage - 1 > curPage)
        {
            mapNextBtn.setVisibility(View.VISIBLE);
        }
        if (totalPage > 0)
        {
            mapCurPage.setVisibility(View.VISIBLE);
            mapCurPage.setText(String.valueOf(curPage + 1) + "/" + String.valueOf(totalPage));
        }
    }

    /**
     * 实现上传callback，自动上传
     */
    @Override
    public RadarUploadInfo onUploadInfoCallback()
    {
        RadarUploadInfo info = new RadarUploadInfo();
        info.comments = userComment;
        info.pt = pt;
        return info;
    }

    //获取周围用户信息
    @Override
    public void onGetNearbyInfoList(RadarNearbyResult result, RadarSearchError radarSearchError)
    {

        //添加显示多个周边配送员的测试，不删除，以后要用
        /*result= new RadarNearbyResult();
        newsFragmentService = new NewsFragmentService();
        result = newsFragmentService.addSelfRadarNearbyResult();*/

        //        System.out.println("==========,_20160521_190717,,radarSearchError.toString()="+radarSearchError.toString());//;

        if (radarSearchError == RadarSearchError.RADAR_NO_ERROR)
        {
            Toast.makeText(getActivity(), "查询周边成功_20160527_202022", Toast.LENGTH_LONG)
                    .show();
            // 获取成功
            listResult = result;
            curPage = result.pageIndex;
            totalPage = result.pageNum;
            // 处理数据
            parseResultToList(listResult);
            parseResultToMap(listResult);
            clearRstBtn.setEnabled(true);
        }
        else
        {
            // 获取失败
            curPage = 0;
            totalPage = 0;
            String makeText = "查询周边失败," + radarSearchError.toString() + ";当前用户位置：" + pt.toString();
            Toast.makeText(getActivity(), makeText, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onGetUploadState(RadarSearchError error)
    {

        if (error == RadarSearchError.RADAR_NO_ERROR)
        {
            // 上传成功
            if (!uploadAuto)
            {
                Toast.makeText(getActivity(), "单次上传位置成功", Toast.LENGTH_LONG)
                        .show();
            }
        }
        else
        {
            // 上传失败
            if (!uploadAuto)
            {
                Toast.makeText(getActivity(), "单次上传位置失败", Toast.LENGTH_LONG)
                        .show();
            }
        }
    }

    @Override
    public void onGetClearInfoState(RadarSearchError error)
    {

        if (error == RadarSearchError.RADAR_NO_ERROR)
        {
            // 清除成功
            Toast.makeText(getActivity(), "清除位置成功", Toast.LENGTH_LONG)
                    .show();
        }
        else
        {
            // 清除失败
            Toast.makeText(getActivity(), "清除位置失败", Toast.LENGTH_LONG)
                    .show();
        }
    }

    @Override
    public void onMapClick(LatLng point)
    {

        mBaiduMap.hideInfoWindow();
    }

    @Override
    public boolean onMapPoiClick(MapPoi poi)
    {


        return false;
    }

    @Override
    public boolean onMarkerClick(Marker marker)
    {

        mBaiduMap.hideInfoWindow();
        if (marker != null)
        {
            popupText = new TextView(getActivity());
            popupText.setBackgroundResource(R.drawable.popup);
            popupText.setTextColor(0xFF000000);
            popupText.setText(marker.getExtraInfo().getString("des"));
            mBaiduMap.showInfoWindow(new InfoWindow(popupText, marker.getPosition(), -47));
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(marker.getPosition());
            mBaiduMap.setMapStatus(update);
            return true;
        }
        else
        {
            return false;
        }
    }

    @Override
    public void onPause()
    {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void onResume()
    {
        mMapView.onResume();
        super.onResume();
        mTabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#B0E2FF"));
    }

    @Override
    public void onDestroy()
    {
        // 退出时销毁定位
        mLocClient.stop();
        // 释放周边雷达相关
        RadarSearchManager.getInstance().removeNearbyInfoListener(this);
        RadarSearchManager.getInstance().clearUserInfo();
        RadarSearchManager.getInstance().destroy();
        // 释放地图
        ff3.recycle();
        mMapView.onDestroy();
        mBaiduMap = null;
        super.onDestroy();
    }

    // 定位SDK回调
    @Override
    public void onReceiveLocation(BDLocation arg0)
    {

        if (arg0 == null || mBaiduMap == null)
        {
            return;
        }
        pt = new LatLng(arg0.getLatitude(), arg0.getLongitude());

        //        System.out.println("========,_20151231_095018,,pt.toString()=" + pt.toString());//;

        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(arg0.getRadius())
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(100).latitude(arg0.getLatitude())
                .longitude(arg0.getLongitude()).build();
        if (mBaiduMap != null)
        {
            mBaiduMap.setMyLocationData(locData);
        }

    }

    public class MyOnPageChangeListener implements OnPageChangeListener
    {

        @Override
        public void onPageSelected(int arg0)
        {
            if (arg0 == 0)
            {
                // 切换为列表
                index = 0;
                switchBtn.setText("地图");
            }
            else
            {
                // 切换为地图
                index = 1;
                switchBtn.setText("列表");
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2)
        {
        }

        @Override
        public void onPageScrollStateChanged(int arg0)
        {
        }
    }

    /**
     * ViewPager适配器
     */
    public class MyPagerAdapter extends PagerAdapter
    {
        public List<View> mListViews;

        public MyPagerAdapter(List<View> mListViews)
        {
            this.mListViews = mListViews;
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2)
        {
            ((ViewPager) arg0).removeView(mListViews.get(arg1));
        }

        @Override
        public void finishUpdate(View arg0)
        {
        }

        @Override
        public int getCount()
        {
            return mListViews.size();
        }

        @Override
        public Object instantiateItem(View arg0, int arg1)
        {
            ((ViewPager) arg0).addView(mListViews.get(arg1), 0);
            return mListViews.get(arg1);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1)
        {
            return arg0 == (arg1);
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1)
        {
        }

        @Override
        public Parcelable saveState()
        {
            return null;
        }

        @Override
        public void startUpdate(View arg0)
        {
        }
    }

    /**
     * 结果列表listview适配器
     */
    private class RadarResultListAdapter extends BaseAdapter
    {
        public List<RadarNearbyInfo> list;

        public RadarResultListAdapter(List<RadarNearbyInfo> res)
        {
            super();
            this.list = res;
        }

        @Override
        public View getView(int index, View convertView, ViewGroup parent)
        {

            //如果是自带的id，忽略
            if (list != null && list.size() != 0)
            {
                if (list.size() > index)
                {
                    String userIdMapSelfTake = list.get(index).userID;
                    //除去某些情况下自带的id
                    if (userIdMapSelfTake.contentEquals("A7A4CA1AB0FC0EE98A74A4A18EA8673A|124533320387468"))
                    {
                        return null;
                    }
                }
            }

            convertView = View.inflate(getActivity(),
                    R.layout.demo_info_item, null);
            TextView title = (TextView) convertView.findViewById(R.id.title);
            TextView desc = (TextView) convertView.findViewById(R.id.desc);
            title.setTextColor(Color.parseColor("#0000FF"));
            desc.setTextColor(Color.parseColor("#0000FF"));
            if (list == null || list.size() == 0 || index >= list.size())
            {
                desc.setText("");
                title.setText("");
            }
            else
            {
                if (list.get(index).comments == null || list.get(index).comments.equals(""))
                {
                    desc.setText(String.valueOf(list.get(index).distance) + "米" + "_没有备注");
                }
                else
                {
                    desc.setText(String.valueOf(list.get(index).distance) + "米" + "_" + list.get(index).comments);
                }
                title.setText(list.get(index).userID);
            }
            return convertView;
        }

        @Override
        public int getCount()
        {
            if (list == null || (list != null && list.size() < 10))
            {
                return 10;
            }
            else
            {
                return list.size();
            }

        }

        @Override
        public Object getItem(int index)
        {
            if (list == null)
            {
                return new RadarNearbyInfo();
            }
            else
            {
                return list.get(index);
            }

        }

        @Override
        public long getItemId(int id)
        {
            return id;
        }
    }

    public View composeLayout(String s, int i)
    {
        LinearLayout layout = new LinearLayout(getActivity());
        layout.setOrientation(LinearLayout.VERTICAL);
        ImageView iv = new ImageView(getActivity());
        iv.setImageResource(i);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, 5, 0, 0);
        //      layout.addView(iv, lp);
        TextView tv = new TextView(getActivity());
        tv.setGravity(Gravity.CENTER);
        tv.setSingleLine(true);
        tv.setText(s);
        tv.setTextColor(Color.parseColor("#0000FF"));
        tv.setTextSize(20);
        layout.addView(tv, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT));
        return layout;
    }




}

